package com.talent.jiwen_teacher;

import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.talent.jiwen_teacher.base.BaseActivity;
import com.talent.jiwen_teacher.course.CourseFragment;
import com.talent.jiwen_teacher.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen_teacher.http.common.ApiFactory;
import com.talent.jiwen_teacher.http.common.HttpUtil;
import com.talent.jiwen_teacher.http.common.ProgressSubscriber;
import com.talent.jiwen_teacher.http.common.UpdateAppHttpUtil;
import com.talent.jiwen_teacher.http.result.HomePageResult;
import com.talent.jiwen_teacher.my.AboutUsActivity;
import com.talent.jiwen_teacher.my.CreditActivity;
import com.talent.jiwen_teacher.my.MyFragment;
import com.talent.jiwen_teacher.ui.widgets.RemindDialog;
import com.talent.jiwen_teacher.ui.widgets.tableView.TabView;
import com.talent.jiwen_teacher.ui.widgets.tableView.TabViewChild;
import com.talent.jiwen_teacher.util.MaterialDialogUtil;
import com.talent.jiwen_teacher.util.SPConstant;
import com.talent.jiwen_teacher.util.SPUtil;
import com.talent.jiwen_teacher.util.Validators;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.vector.update_app.listener.IUpdateDialogFragmentListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;

public class IndexActivity extends BaseActivity {
    private static TabView myTabView;

    public static boolean tab1Checked = false;
    public static boolean tab2checked = false;
    public static boolean tab3Checked = false;

    private boolean backPressed;
    private Handler handler = new Handler();//再按一次退出

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_index;
    }

    @Override
    public String titleName() {
        return null;
    }

    @Override
    protected void initData() {
        myTabView = (TabView)findViewById(R.id.myTabView);
        initTabView(0);
        setHeadVisibility(View.GONE);
        showUpdate();
        getHomePageInfo();

        //显示福利dialog
//        if (SPUtil.booleanOut(SPConstant.SHOW_WELFARE_DIALOG)){
//            WelFareDialog welFareDialog = new WelFareDialog(this);
//            welFareDialog.setCancelable(false);
//            welFareDialog.show();
//            SPUtil.booleanIn(SPConstant.SHOW_WELFARE_DIALOG , false);
//        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (tab1Checked) {
            initTabView(0);
            tab1Checked = false;
        } else if (tab2checked) {
            initTabView(1);
            tab2checked = false;
        } else if (tab3Checked){
            initTabView(2);
            tab3Checked = false;
        }
    }


    private void getHomePageInfo(){
        Map<String, String> map = new HashMap<>();
        map.put("teacherId" , SPUtil.stringOut(SPConstant.USER_ID));

        Observable observable = ApiFactory.getEducationApiSingleton().getHomePageInfo(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<HomePageResult>(this) {
            @Override
            protected void _onNext(HomePageResult homePageResult) {
                int lastTimes=SPUtil.intOut(SPConstant.THIS_CREDIT_TIMES);
                if(lastTimes>0){
                    if(lastTimes!=homePageResult.getDiscreditCount()){
                        showCreditDialog(homePageResult.getDiscreditCount());
                    }
                }else{
                    showCreditDialog(homePageResult.getDiscreditCount());
                }
                String NimToken=homePageResult.getNIMToken();
                if(!Validators.isEmpty(NimToken)){
                    SPUtil.stringIn(SPConstant.NIM_TOKEN,NimToken);
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,false);
    }

    /**显示失信dialog
     *
     * @param discreditCount
     */
    private void showCreditDialog(final int discreditCount){
        if (discreditCount < 3 && discreditCount > 0){
            RemindDialog remindDialog = MaterialDialogUtil.getRemindDialog(IndexActivity.this, R.mipmap.dialog_lose_credit, "你有" + discreditCount + "次失信记录"
                    , "取消", "查看", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            SPUtil.intIn(SPConstant.THIS_CREDIT_TIMES,discreditCount);
                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            SPUtil.intIn(SPConstant.THIS_CREDIT_TIMES,discreditCount);
                            intentActivity(CreditActivity.class);
                        }
                    });
            remindDialog.show();
        }else if (discreditCount >= 4){
            RemindDialog dialog = MaterialDialogUtil.getRemindDialog(IndexActivity.this, R.mipmap.dialog_lose_credit, "您的失信次数已达上限,账户已被冻结,请联系客服专员解决"
                    , "取消", "去联系", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            intentActivity(AboutUsActivity.class);
                        }
                    });
            dialog.show();
        }
    }

    /**版本更新
     *
     */
    private void showUpdate(){

        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        Map<String, String> params = new HashMap<String, String>();
        params.put("application_type", "4");

        new UpdateAppManager
                .Builder()
                //必须设置，当前Activity
                .setActivity(this)
                //必须设置，实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil())
                //必须设置，更新地址
                .setUpdateUrl("abcd")
                //以下设置，都是可选
                //设置请求方式，默认get
                .setPost(true)
                //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
                .setParams(params)
                //设置点击升级后，消失对话框，默认点击升级后，对话框显示下载进度
//                .hideDialogOnDownloading()
                //设置头部，不设置显示默认的图片，设置图片后自动识别主色调，然后为按钮，进度条设置颜色
                .setTopPic(R.mipmap.top_5)
                //为按钮，进度条设置颜色，默认从顶部图片自动识别。
                //.setThemeColor(ColorUtil.getRandomColor())
                //设置apk下砸路径，默认是在下载到sd卡下/Download/1.0.0/test.apk
                .setTargetPath(path)
                //设置appKey，默认从AndroidManifest.xml获取，如果，使用自定义参数，则此项无效
                //.setAppKey("ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f")
                //不显示通知栏进度条
                .dismissNotificationProgress()
                //是否忽略版本
                //.showIgnoreVersion()
                .setUpdateDialogFragmentListener(new IUpdateDialogFragmentListener() {
                    @Override
                    public void onUpdateNotifyDialogCancel(UpdateAppBean updateApp) {
                        //用户点击关闭按钮，取消了更新，如果是下载完，用户取消了安装，则可以在 onActivityResult 监听到。

                    }
                })
                .build()
                //检测是否有新版本
                .checkNewApp(new UpdateCallback() {
                    /**
                     * 解析json,自定义协议
                     *
                     * @param json 服务器返回的json
                     * @return UpdateAppBean
                     */
                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        try {
                            JSONObject jsonObject = new JSONObject(json);
                            updateAppBean
                                    //（必须）是否更新Yes,No
                                    .setUpdate(jsonObject.optString("update"))
                                    //（必须）新版本号，
                                    .setNewVersion(jsonObject.optString("new_version"))
                                    //（必须）下载地址
                                    .setApkFileUrl(jsonObject.optString("apk_file_url"))
                                    //（必须）更新内容
                                    .setUpdateLog(jsonObject.optString("update_log"))
                                    //大小，不设置不显示大小，可以不设置
                                    .setTargetSize(jsonObject.optString("target_size"))
                                    //是否强制更新，可以不设置
                                    .setConstraint(false)
                                    //设置md5，可以不设置
                                    .setNewMd5(jsonObject.optString("new_md51"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        return updateAppBean;
                    }

                    @Override
                    protected void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                        updateAppManager.showDialogFragment();
                    }

                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {
//                        CProgressDialogUtils.showProgressDialog(LoginActivity.this);
                    }

                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {
//                        CProgressDialogUtils.cancelProgressDialog(LoginActivity.this);
                    }
//
                    /**
                     * 没有新版本
                     */
                    @Override
                    public void noNewApp(String error) {

//                        Toast.makeText(SplashActivity.this, "没有新版本", Toast.LENGTH_SHORT).show();
                    }
                });

    }


    HomeFragment homeFragment;
    CourseFragment courseFragment;
    MyFragment myFragment;
    private void initTabView(int defaultPosition){
        homeFragment=new HomeFragment();
        courseFragment=new CourseFragment();
        myFragment= new MyFragment();

        List<TabViewChild> tabViewChildList=new ArrayList<>();
        TabViewChild tabViewChild01=new TabViewChild(R.mipmap.tab_home_selected ,R.mipmap.tab_home_normal,getString(R.string.tab_home),  homeFragment);
        TabViewChild tabViewChild02=new TabViewChild(R.mipmap.tab_teacher_selected,R.mipmap.tab_teacher_normal,getString(R.string.tab_course1),  courseFragment);
        TabViewChild tabViewChild03=new TabViewChild(R.mipmap.tab_my_selected,R.mipmap.tab_my_normal,getString(R.string.tab_my),  myFragment);

        tabViewChildList.add(tabViewChild01);
        tabViewChildList.add(tabViewChild02);
        tabViewChildList.add(tabViewChild03);

        myTabView.setTabViewDefaultPosition(defaultPosition);
        myTabView.setTabViewChild(tabViewChildList,getSupportFragmentManager());
        myTabView.setOnTabChildClickListener(new TabView.OnTabChildClickListener() {
            @Override
            public void onTabChildClick(int  position, ImageView currentImageIcon, TextView currentTextView) {
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (backPressed) {
            finish();
        } else {
            showToast("再按一次退出");
            backPressed = true;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    backPressed = false;
                }
            }, 2000L);
        }
    }

//    @Override
//    protected void onSaveInstanceState(Bundle outState) {
//        //在FragmentActivity保存所有Fragment状态前把Fragment从FragmentManager中移除掉。
//        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//        if(homeFragment!=null){
//            transaction.remove(homeFragment);
//        }
//        if(courseFragment!=null){
//            transaction.remove(courseFragment);
//        }
//
//        if(myFragment!=null){
//            transaction.remove(myFragment);
//        }
//        transaction.commitAllowingStateLoss();
//        super.onSaveInstanceState(outState);
//    }
}